#! /usr/bin/env python
#coding=utf-8
import time, sys
#from charts.models import *
import datetime
from datetime import date
import os


from uliweb import expose
from sqlalchemy import *
from uliweb.orm import *
from uliweb.orm import do_
from uliweb.utils.pyini import Ini
from sqlalchemy.sql import select
from sqlalchemy.sql import and_, or_, not_

sys.path.insert(0, '../apps')

from departments.models import *
from myuser.models import *

from systems.models import *
from requirements.models import *
from assignments.models import *

from functions.models import *
from tasks.models import *
from charts.models import *

from resource.models import *
from tests.models import *
from plan.models import *
from messages.models import *
from tables.models import *
from notices.models import *
from ticket.models import *

from risks.models import *
from weekreport.models import *
from uliweb.core.html import Tag
from uliweb import url_for
#os.chdir('..')
#
#from uliweb.core.SimpleFrame import Dispatcher
#settings = {'ORM/DEBUG_LOG':True, 'ORM/AUTO_CREATE':False}
#app = Dispatcher(apps_dir='apps', start=False, default_settings=settings)
#sys.path.insert(0, 'apps')


def get_db_connection():
    #connect = Ini('../apps/settings.ini').ORM.CONNECTION
#    connect='sqlite:///../database.db'
#    db = get_connection(connect)
    
    db = get_connection('mysql://ctasks:123456@localhost/ctasks?charset=utf8')
    return db

def strtodatetime(datestr,format):       
    return datetime.date(*time.strptime(datestr, format)[:3]) 

def getMonth(): 
    return str(datetime.date.today())[5:7] 

def getYear():   
    return str(datetime.date.today())[0:4] 

def get_next_month():
    #获取报表当前月第一天
    format="%Y-%m-%d" 
        
    #获取当前月份 是一个字符串    
    year =  getYear()
    month = getMonth()
    oneday = datetime.timedelta(days=1)
    
    #规定每月1日1时0分0秒开始运行月报跑批程序

    #next_month是季度末日期，即为本月末日期
    next_month = long(month)+1
    #判断当前月是否为12月，若为12月则月份赋值1月，年度增加1年
    next_year = str(year)
    if(next_month == 13):
        next_month = 1
        next_year = str(long(year)+1)
    next_month = str(next_month)
    
    #计算季度初始日期，即为本季度第一个月1日
    #first_month = long(month) - 2
    first_month = long(month)
    first_month = str(first_month)
    first_day = str(year) + '-' + first_month + '-01'
    last_day = next_year + '-' + next_month + '-01'
    
    month_first_day = strtodatetime(first_day,format)
    month_last_day = strtodatetime(last_day,format)-oneday

    
    return  month_first_day,month_last_day

  
def get_month():
    #获取报表当前月第一天

    format="%Y-%m-%d" 
        
    #获取当前月份 是一个字符串    
    year =  getYear()
    month = getMonth()
    oneday = datetime.timedelta(days=1)
    
    #规定每月1日1时0分0秒开始运行月报跑批程序
    if long(month) == 1:
        month = 12
        year = long(year) - 1
    else:
        month = long(month) - 1
        
    #########################################
    
    #转换当前月份的显示格式
    month_view = str(month) + '月'
    
    
    #next_month是季度末日期，即为本月末日期
    next_month = long(month)+1
    #判断当前月是否为12月，若为12月则月份赋值1月，年度增加1年
    next_year = str(year)
    if(next_month == 13):
        next_month = 1
        next_year = str(long(year)+1)
    next_month = str(next_month)
    
    #计算季度初始日期，即为本季度第一个月1日
    #first_month = long(month) - 2
    first_month = long(month)
    first_month = str(first_month)
    first_day = str(year) + '-' + first_month + '-01'
    last_day = next_year + '-' + next_month + '-01'
    
    month_first_day = strtodatetime(first_day,format)
    month_last_day = strtodatetime(last_day,format)-oneday
#    month_first_day = strtodatetime('2010-12-01',format)
#    month_last_day = strtodatetime('2011-01-01',format)-oneday
    
    return  month_first_day,month_last_day,month_view

#def get_last_month():
#    #获取报表当前时间
#    def getMonth(): 
#        return str(datetime.date.today())[5:7] 
#    def getYear():   
#        return str(datetime.date.today())[0:4] 
#    
#    format="%Y-%m-%d" 
#    #获取当前月份 是一个字符串    
#    year =  getYear()
#    month = getMonth()
#    
#    #获取上上月月份
#    if long(month) == 1:
#        month = 11
#        year = long(year) - 1 
#    elif long(month) == 2:
#        month = 12
#        year = long(year) - 1
#    else:
#        month = long(month) - 2  
##    print str(year)+'-'+str(month)+'-'+'01'
##    print strtodatetime(str(year)+'-'+str(month)+'-'+'01',format)
#    return  str(strtodatetime(str(year)+'-'+str(month)+'-'+'01',format))[0:4]+str(strtodatetime(str(year)+'-'+str(month)+'-'+'01',format))[5:7]

def get_quarter():
    #获取报表当前月第一天    
    format="%Y-%m-%d" 
        
    #获取当前月份 是一个字符串    
    year =  getYear()
    month = getMonth()
    oneday = datetime.timedelta(days=1)
    #规定每月1日1时0分0秒开始运行月报跑批程序
    if long(month) == 1:
        month = 12
        year = long(year) - 1
    else:
        month = long(month) - 1
            
     #########################################
    
    #判断本月末是否是季度末
    quarter = long(month)
    if(quarter <> 3) and (quarter <> 6) and (quarter <> 9) and (quarter <> 12):
        sys.exit()
    
    #获取当前季度信息
    if(quarter == 3):
        quarter_view = '一季度'
    elif(quarter == 6):
        quarter_view = '二季度'
    elif(quarter == 9):
        quarter_view = '三季度'
    elif(quarter == 12):
        quarter_view = '四季度'
    
    #next_month是季度末日期，即为本月末日期
    next_month = long(month)+1
    #判断当前月是否为12月，若为12月则月份赋值1月，年度增加1年
    next_year = str(year)
    if(next_month == 13):
        next_month = 1
        next_year = str(long(year)+1)
    next_month = str(next_month)
    
    #计算季度初始日期，即为本季度第一个月1日
    if long(month) == 1:
        first_month = 11
    elif long(month) == 2:
        first_month = 12
    else:
        first_month = long(month) - 2
    #first_month = long(month)
    first_month = str(first_month)
    if(first_month == 11 or first_month == 12):
        year = long(year)-1
    next_month = str(next_month)
    
    year = str(year)
    first_day = str(year) + '-' + first_month + '-01'
    last_day = next_year + '-' + next_month + '-01'
    
    month_first_day = strtodatetime(first_day,format)
    month_last_day = strtodatetime(last_day,format)-oneday
    
#    month_first_day = strtodatetime('2010-10-01',format)
#    month_last_day = strtodatetime('2011-01-01',format)-oneday
    
    return  month_first_day,month_last_day,quarter_view,quarter
    

def get_next_quarter():
    #获取报表当前月第一天    
    format="%Y-%m-%d" 
        
    #获取当前月份 是一个字符串    
    year =  getYear()
    month = getMonth()
    oneday = datetime.timedelta(days=1)
    #规定每月1日1时0分0秒开始运行月报跑批程序
    if long(month) == 1:
        month = 12
        year = long(year) - 1
    else:
        month = long(month) - 1
            
     #########################################
    
    #判断本月末是否是季度末
    quarter = long(month)
    if(quarter <> 3) and (quarter <> 6) and (quarter <> 9) and (quarter <> 12):
        sys.exit()
    
    #获取当前季度信息
#    if(quarter == 3):
#        quarter_view = '一季度'
#    elif(quarter == 6):
#        quarter_view = '二季度'
#    elif(quarter == 9):
#        quarter_view = '三季度'
#    elif(quarter == 12):
#        quarter_view = '四季度'
    
    #next_month是季度末日期，即为本月末日期
    next_month = long(month)+4
    #判断当前月是否为12月，若为12月则月份赋值1月，年度增加1年
    next_year = str(year)
#    print '+++++++++',next_month,next_year
    if(next_month == 13):
        next_month = 1
        next_year = str(long(year)+1)
    elif next_month == 14:
        next_month = 2
        next_year = str(long(year)+1)
    elif next_month == 15:
        next_month = 3
        next_year = str(long(year)+1)
    elif next_month == 16:
        next_month = 4
        next_year = str(long(year)+1)
    
    next_month = str(next_month)
#    print '+++++++++-------',next_month,next_year
    #计算季度初始日期，即为本季度第一个月1日
    if long(next_month) == 1:
        first_month = 10
    elif long(next_month) == 2:
        first_month = 11
    elif long(next_month) == 3:
        first_month = 12
    else:
        first_month = long(next_month) - 3
    #first_month = long(month)
    first_month = str(first_month)
    if(first_month == 11 or first_month == 12 ):
        year = long(next_year)-1
    elif(first_month == 13):
        first_month = 1
        year = long(next_year)
    elif(first_month == 14):
        first_month = 2
        year = long(next_year)
    
#    print '-------',first_month,year
    next_month = str(next_month)
    
    year = str(year)
    first_day = str(year) + '-' + first_month + '-01'
    last_day = next_year + '-' + next_month + '-01'
    
    month_first_day = strtodatetime(first_day,format)
    month_last_day = strtodatetime(last_day,format)-oneday
    
#    month_first_day = strtodatetime('2010-10-01',format)
#    month_last_day = strtodatetime('2011-01-01',format)-oneday
    
    return  month_first_day,month_last_day


def get_week():
    #获取本周的第一天和最后一天
    today = date.today()
    first_day = today - datetime.timedelta(days=(today.weekday()+2)%7)
    last_day = first_day + datetime.timedelta(days=6)
    
#    sixday = datetime.timedelta(days=6)
#    oneday = datetime.timedelta(days=1)
#    twoday = datetime.timedelta(days=2)
#
#    last_day = datetime.date.today()# - twoday
#    first_day = datetime.date.today() - sixday
    #需要重新跑批周报时，需要修改下面两注释行开始、结束时间，取消注释，完成后再注释
#    format="%Y-%m-%d" 
#    first_day = strtodatetime('2011-01-01',format)
#    last_day = strtodatetime('2011-11-28',format)
#    print 'first_day',first_day
#    print 'last_day',last_day
    return  first_day,last_day

def get_next_week():
    today = date.today()
    first_day = today + datetime.timedelta(days=(7-(today.weekday()+2)%7))
    last_day = first_day + datetime.timedelta(days=6)
    return  first_day,last_day

def get_last_week():
    #获取本周的第一天和最后一天
    today = date.today()
    first_day = today - datetime.timedelta(days=(today.weekday()+2)%7)
    last_day = first_day + datetime.timedelta(days=6)
    first_day = first_day - datetime.timedelta(days=7)
    last_day = last_day - datetime.timedelta(days=7)
    return  first_day,last_day


def get_year():
    #获取报表当前月第一天
    def getMonth(): 
        return str(datetime.date.today())[5:7] 
#    def strtodatetime(datestr,format):       
#        return datetime.date(*time.strptime(datestr, format)[:3])   
    def getYear():   
        return str(datetime.date.today())[0:4] 
    
    format="%Y-%m-%d" 
    
    
    #获取当前月份 是一个字符串    
    year =  getYear()
    month = getMonth()
    oneday = datetime.timedelta(days=1)
    year = long(year) - 1
    next_year = str(long(year)+1)
#    #规定每月1日1时0分0秒开始运行月报跑批程序
#    if long(month) == 1:
#        month = 12
#        year = long(year) - 1
#    else:
#        month = long(month) - 1
#        
#    #########################################
#    
#    #转换当前月份的显示格式
#    month_view = str(month) + '月'
#    
#    #判断本月末是否是季度末
#    #quater = long(month)
#    #if(quater < 3) and (quater <> 3) and (quater <> 6) and (quater <> 9) and (quater <> 12):
#    #    sys.exit()
#    
#    #next_month是季度末日期，即为本月末日期
#    next_month = long(month)+1
#    #判断当前月是否为12月，若为12月则月份赋值1月，年度增加1年
#    next_year = str(year)
#    if(next_month == 13):
#        next_month = 1
#        next_year = str(long(year)+1)
#    next_month = str(next_month)
#    
#    #计算季度初始日期，即为本季度第一个月1日
#    #first_month = long(month) - 2
#    first_month = long(month)
#    first_month = str(first_month)
    first_day = str(year) + '-' + '01' + '-01'
    last_day = next_year + '-' + '01' + '-01'
    
    month_first_day = strtodatetime(first_day,format)
    month_last_day = strtodatetime(last_day,format)-oneday
#    month_first_day = strtodatetime('2010-12-01',format)
#    month_last_day = strtodatetime('2011-01-01',format)-oneday
    
    return  month_first_day,month_last_day

#函数datetimetodate为将datetime转换为date型
def datetimetodate(input_datetime):
    out_date = str(input_datetime)[0:10]
    format="%Y-%m-%d";
    bd=strtodatetime(out_date,format)
    return bd

#函数datediff计算两个日期之间的天数
def datediff(beginDate,endDate):
    beginDate = str(beginDate)[0:10]
    endDate = str(endDate)[0:10]
    format="%Y-%m-%d";
    bd=strtodatetime(beginDate,format)
    ed=strtodatetime(endDate,format)
    #如果开始日期大于结束日期，则天数等于开始日期减结束日期
    if bd>ed:
        bd_t = bd
        bd = ed
        ed = bd_t
#    bd = datetime.date(beginDate)
#    ed = datetime.date(endDate)
#    print 'bd,ed',bd,ed
    oneday=datetime.timedelta(days=1)
    count=0
    #print ed
    if ed<bd or bd == None or ed == None:
        return count
    while bd!=ed:
        ed=ed-oneday
        count+=1
    return count

#以下get_logger函数为打印报表跑批过程中程序处理情况的日志

FORMAT = "%(levelname)-8s %(asctime)-15s %(filename)s,%(lineno)d] %(message)s"
LOG_FILENAME = 'report.log'

def get_logger(format=FORMAT, datafmt=None):
    global log
    import logging
    import logging.handlers
    
#       handler = logging.StreamHandler()
    handler = logging.handlers.RotatingFileHandler(
                    LOG_FILENAME, maxBytes=1024*1024*1024*50, backupCount=5)
    fmt = logging.Formatter(format, datafmt)
    handler.setFormatter(fmt)
    
    log = logging.getLogger('uliweb')
    log.addHandler(handler)
    log.setLevel(logging.INFO)
    return log

log = get_logger()

#初始化提醒信息
def get_init_message_data():
    data={}
    data['memo'] = ''
    data['type'] = ''
    data['read_flag'] = False
    data['user'] = ''
    data['sender'] = None
    return data

#存储提醒信息，在消息model明确后修改
def save_new_message(data):
    News_Message = get_model('message')
    
    for row in data:
#        print 'row',row
        r = News_Message(**row)
        r.save()
        